package com.cy.device.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @author: jiangwang
 * @created: 2023/10/24 14:32
 */
@Configuration
@ConditionalOnBean(RabbitmqProperties.class)
public class RabbitmqConfig {

    @Autowired
    private RabbitmqProperties rmqProperties;

    @Bean
    public ConnectionFactory connectionFactory() {
        // 必须在构造函数里写host
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rmqProperties.getHost());
        connectionFactory.setUsername(rmqProperties.getUsername());
        connectionFactory.setPassword(rmqProperties.getPassword());
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }

    @Bean
    @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        // 设置默认exchange
        rabbitTemplate.setExchange(rmqProperties.getExchange());
        return rabbitTemplate;
    }
}
